package com.jeehentor.ai.core;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jeehentor.ai.config.AiSessionManager;
import com.jeehentor.ai.dto.ChatMessage;
import com.jeehentor.ai.entity.AiPlatformConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.util.*;
/**
 * @Description : DeepSeek AI 接口实现类（非流式）
 * @Author : wzd
 * @Date : 2025/4/17 14:26
 * @Version : 1.0
 **/

@Slf4j
@RequiredArgsConstructor
public class DeepSeekClient implements AiClient {

    private final AiPlatformConfig config;
    private final WebClient webClient = WebClient.create();
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final AiSessionManager sessionManager;

    @Override
    public String chat(String prompt, String sessionId) {
        try {
            Map<String, Object> body = buildRequestWithContext(prompt, sessionId, false);
            String json = webClient.post()
                    .uri(config.getBaseUrl() + "/v1/chat/completions")
                    .headers(h -> h.setBearerAuth(config.getApiKey()))
                    .bodyValue(body)
                    .retrieve()
                    .bodyToMono(String.class)
                    .block();

            String content = objectMapper.readTree(json).path("choices").path(0).path("message").path("content").asText();

            // 保存到上下文
            sessionManager.appendMessage(sessionId, "user", prompt);
            sessionManager.appendMessage(sessionId, "assistant", content);

            return content;

        } catch (Exception e) {
            return "AI调用失败：" + e.getMessage();
        }
    }

    @Override
    public Flux<String> streamChat(List<ChatMessage> messages, String sessionId) {
        Map<String, Object> body = new HashMap<>();
        body.put("model", config.getModel());
        body.put("stream", true);
        body.put("messages", messages); // 👈 传入上下文

        return webClient.post()
                .uri(config.getBaseUrl() + "/v1/chat/completions")
                .headers(h -> h.setBearerAuth(config.getApiKey()))
                .bodyValue(body)
                .retrieve()
                .bodyToFlux(String.class)
                .flatMap(line -> {
                    if (line.startsWith("data: ")) {
                        line = line.substring(6).trim();
                    }
                    if ("[DONE]".equals(line)) return Flux.empty();
                    try {
                        JsonNode node = objectMapper.readTree(line);
                        return Flux.just(
                                node.path("choices").path(0).path("delta").path("content").asText("")
                        );
                    } catch (Exception e) {
                        return Flux.empty();
                    }
                });
    }



    private Map<String, Object> buildRequestWithContext(String prompt, String sessionId, boolean stream) {
        List<Map<String, String>> messages = new ArrayList<>(sessionManager.getHistory(sessionId));
        messages.add(Map.of("role", "user", "content", prompt));

        Map<String, Object> req = new HashMap<>();
        req.put("model", config.getModel());
        req.put("temperature", config.getTemperature());
        req.put("stream", stream);
        req.put("messages", messages);
        return req;
    }
}